#!/usr/bin/env python3

"""
 该脚本为 lv_label_set_text添加
 lv_obj_set_user_data 函数以便用于国际化
"""

import re
import argparse
import os
import shutil

def process_file(input_file, make_copy):
    # 精确匹配lv_label_set_text的标准调用格式
    pattern = re.compile(
        r'^(\s*)'                          # 缩进
        r'(lv_label_set_text\s*\()'        # 函数名和左括号 
        r'\s*([\w\->\.]+)\s*,\s*'           # 组件名
        r'_\("([\w_]+)"\)\s*\)\s*;?'      # 带翻译的字符串参数
        r'.*'
    )

    if make_copy:
        base, ext = os.path.splitext(input_file)
        output_file = f"{base}_modified{ext}"
        shutil.copy2(input_file, output_file)
        file_to_process = output_file
    else:
        output_file = input_file
        file_to_process = input_file + ".tmp"

    with open(input_file, 'r', encoding='utf-8') as f_in, \
         open(file_to_process, 'w', encoding='utf-8') as f_out:

        for line in f_in:
            line = line.rstrip('\n')
            match = pattern.match(line)
            
            if match:
                indent = match.group(1)
                widget_name = match.group(3)
                string_id = match.group(4)

                # 严格重建标准语句
                new_line = f"{indent}lv_label_set_text({widget_name}, _(\"{string_id}\"));\n"
                new_line += f"{indent}lv_obj_set_user_data({widget_name}, \"{string_id}\");  //* add user data"
                
                f_out.write(new_line + '\n')
            else:
                f_out.write(line + '\n')

    if not make_copy:
        os.replace(file_to_process, output_file)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('input_file')
    parser.add_argument('--copy', action='store_true')
    args = parser.parse_args()

    if not os.path.isfile(args.input_file):
        print(f"Error: File {args.input_file} not found")
        exit(1)

    process_file(args.input_file, args.copy)
    print("Processing completed successfully")